package realtime;

import java.awt.Cursor;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import application.*;

import messagepasser.*;

public class SendDocumentState extends TimerTask {
	private MessagePasser myPasser;
	private Timer myTimer;
	private Lab0Test app;
	private String consistentState;
	
	public SendDocumentState(MessagePasser passer, Timer t, Lab0Test app) {
		myPasser = passer;
		myTimer = t;
		this.app = app;
		consistentState = "";
	}
	
	public void run() {
		
		
		diff_match_patch dmp = new diff_match_patch();
		String currText = app.recvTextArea.getText();
		
		LinkedList<diff_match_patch.Diff> diff = dmp.diff_main (consistentState, currText);
		dmp.diff_cleanupSemantic(diff);
		LinkedList<diff_match_patch.Patch> patchList = dmp.patch_make(consistentState, currText, diff);
		
			myPasser.send(new TimeStampedMessage(app.destField.getText(), myPasser.getMyName(), "abc",
					"abc", patchList, false, false));
		
		Message data = (myPasser.receive());
		
		
		if (data != null) {
			if (myPasser.getMyName().contains(data.getPhySender())) {
				return;
			}
			LinkedList<diff_match_patch.Patch> patches = (LinkedList<diff_match_patch.Patch>) (data.getPayload()); 
			Object[] result = dmp.patch_apply(patches, currText);
			consistentState = (String)result[0];
			int position = app.recvTextArea.getCaretPosition();
			app.recvTextArea.setText((String)result[0]);
			if (position > app.recvTextArea.getCaretPosition()) {
				app.recvTextArea.setCaretPosition(position);
			}
			
		}
		
	}
}

